package com.example.foreapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

public class ForeAppService extends Service{
	
	private DbOpenHelper db;
	boolean flag;
	private AlarmManager alarmMgr;
	private SimpleDateFormat sdf;
	private static final String TAG="ForeappService";
	PendingIntent alarmIntent=null;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		db=DbUtil.getIns(this);
		flag=false;
		sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		alarmMgr=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
	}


	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
//		Log.d(TAG, "onStart,"+(intent==null?"null":"intent"));
//		startTask(intent);
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d(TAG, "onStartCommand,"+(intent==null?"null":"intent"));
		if(intent!=null){
			if(intent.getExtras()!=null){
				String action=intent.getExtras().getString("action");
				if("stop".equals(action)){
					stopServiceAlarm();
					return Service.START_NOT_STICKY;
				}
			}
		}
		startTask(intent);
		return super.onStartCommand(intent, flags, startId);
	}
	
	private void startTask(Intent mIntent){
		Log.d(TAG, "time:"+Calendar.getInstance().get(Calendar.MINUTE)+":"+Calendar.getInstance().get(Calendar.SECOND)+","
	+(mIntent==null?"null":mIntent.getBooleanExtra("task", false)));
//		mIntent.getExtras().getBoolean("task");
		if(mIntent!=null){
			boolean istask=mIntent.getBooleanExtra("task", false);
			if(istask){
				saveForeAppActivity(getForeAppActivity());
			}else{
				if(!flag){
					Intent intent=new Intent(this.getApplicationContext(),ForeAppService.class);
					intent.putExtra("task", true);
					alarmIntent=PendingIntent.getService(getApplicationContext(), 0, intent, 0);
					alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 1000, alarmIntent);
					flag=true;
				}
			}
		}
	}
	
	private void stopServiceAlarm(){
		alarmMgr.cancel(alarmIntent);
		this.stopSelf();
	}
	
	/*
	 * 获取当前在前台的App和Activity
	 */
	private ActivityInfo getForeAppActivity(){
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
		
		String packageName = rti.get(0).topActivity.getPackageName();
		String className=rti.get(0).topActivity.getClassName();
		String time=sdf.format(Calendar.getInstance().getTime());
		 PackageManager pm = this.getPackageManager(); // 获得PackageManager对象  
	     Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);  
	    mainIntent.setPackage(packageName);
	    List<ResolveInfo> resolveInfos = pm  
                .queryIntentActivities(mainIntent, PackageManager.MATCH_DEFAULT_ONLY);
	    Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));  
	    Log.d(TAG, "name:"+className+",size="+resolveInfos.size());
	    String label=null;
	    if(resolveInfos.size()>0){
	    	label=(String)resolveInfos.get(0).loadLabel(pm);
	    }
	    ActivityInfo info=new ActivityInfo(time, label);
	    info.setClassName(className);
	    info.setPkgName(packageName);
		return info;
	}
	
	private void saveForeAppActivity(ActivityInfo info){
		if(db.findActivity(info)){
			db.updateRecode(info);
		}else{
			db.insertRcode(info.getTime(), info.getLabel()==null?"unknow":info.getLabel(), info.getPkgName(), info.getClassName());
		}
	}
	
	
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		db.close();
		flag=false;
		Log.d(TAG, "ForeAppService was cancel");
		db=null;
	}

}
